<?php

namespace app\admin\service;

use app\admin\dao\PromotionGroupDao;
use app\admin\dao\PromotionGroupFeedbackDao;
use app\admin\model\UM as UM;
use app\common\model\PromotionAction;
use app\common\model\PromotionEvent;
use app\common\model\PromotionGroup;
use app\common\model\PromotionGroupFeedback;
use ShidianUtil\Exception\DataNotExistException;
use think\exception\ValidateException;

/**
 * Class PromotionGroupService
 * @package app\admin\service
 */
class PromotionGroupService
{
    // dao
    private PromotionGroupDao $promotionGroupDao;

    public function __construct(PromotionGroupDao $promotionGroupDao)
    {
        $this->promotionGroupDao = $promotionGroupDao;
    }

    /**
     * 列表
     * @param UM|null $user
     * @param int|null $page
     * @param int|null $page_size
     * @return array
     */
    public function index(?UM $user, ?int $page = null, ?int $page_size = null): array
    {
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->promotionGroupDao->select($page, $page_size);
    }

    /**
     * 查询
     * @param UM|null $user
     * @param int $id
     * @return PromotionGroup
     */
    public function read(?UM $user, int $id): ?PromotionGroup
    {
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->promotionGroupDao->find($id);
    }

    /**
     * 新增
     * @param UM $user
     * @param array $params
     * @return  PromotionGroup
     */
    public function add(UM $user, array $params): PromotionGroup
    {
        $this->checkRepeat($params['groupName']);

        return $this->promotionGroupDao->insertActive($params, []);
    }

    /**
     * 更新
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return PromotionGroup
     */
    public function modify(UM $user, int $id, array $params): PromotionGroup
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = PromotionGroup::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该对象不存在或已被删除');
        }

        $this->checkRepeat($params['groupName'], $id);

        $allowField = [];
        $this->promotionGroupDao->updateActive($record, $params, $allowField);

        return $record;
    }

    /**
     * 删除
     * @param UM $user
     * @param int $id
     */
    public function rm(UM $user, int $id): void
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = PromotionGroup::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            return;
        }

        $record->isDel = '1';
        $record->save();

    }

    private function checkRepeat($groupName, $id = null)
    {
        $record = PromotionGroup::where('groupName', $groupName)
            ->when(is_id($id), fn($query) => $query->where('id', '<>', $id))
            ->where('isDel', '0')
            ->find();
        if ($record) {
            throw new ValidateException('小组' . $record->groupName . '已经存在，请更换其他名称');
        }
    }

}
